package com.systemframework.aspect;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUtil;
import cn.hutool.http.useragent.UserAgent;
import cn.hutool.http.useragent.UserAgentUtil;
import com.alibaba.fastjson.JSON;

import com.systemframework.annotation.LogAnnotation;
import com.systemframework.constants.Constants;
import com.systemframework.sys.entity.SysLog;
import com.systemframework.sys.service.SysLogService;
import com.systemframework.util.IpKit;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;

/**
 * @author summer
 * @date 2023-03-17 14:08
 */
@Component
@Aspect
@Slf4j
@Order(1)
public class LogAspect {

    private Long startTime=null;

    @Before(value = "@annotation(com.systemframework.annotation.LogAnnotation)")
    public void before(){
        startTime=DateUtil.current();
        log.info("开始执行时间:{}",startTime);
    }

    private SysLogService sysLogService;

    @Autowired
    public void setSysLogService(SysLogService sysLogService) {
        this.sysLogService = sysLogService;
    }

    @AfterReturning(value = "@annotation(com.systemframework.annotation.LogAnnotation)" )
    public void aroundAspect(JoinPoint joinPoint)  {
        HttpServletRequest request = Convert.convert(ServletRequestAttributes.class, RequestContextHolder.getRequestAttributes()).getRequest();
        String ip = IpKit.getRealIp(request);
        UserAgent userAgent = UserAgentUtil.parse(request.getHeader(Constants.USER_AGENT));
        String versionNum = userAgent.getVersion();
        String browserName = userAgent.getBrowser().toString();
        Signature signature = joinPoint.getSignature();
        MethodSignature methodSignature = Convert.convert(MethodSignature.class, signature);
        Method method = methodSignature.getMethod();
        LogAnnotation annotation = method.getAnnotation(LogAnnotation.class);
        Long endTime=DateUtil.current()-startTime;
        SysLog sysLog= new SysLog(versionNum,browserName,ip,Convert.toInt(StpUtil.getLoginId()),annotation.msg(),endTime,signature.getName());
        sysLogService.save(sysLog);
    }
}
